/*
 *   This file is part of Verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *   Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */ 

function random(inf, sup) {
	var pos = sup - inf;
	var rn = Math.random() * pos;
	var rn = Math.round(rn);
	return parseInt(inf) + rn;	
}

function getMainUrl(p) {
	var r = "index.php?tx="+(new Date().getTime()+random(10000,99999));
	if (p!=undefined) {
		r += "&" + p;
	}
	return r;
}

function keepAlive() {
	Ext.Ajax.request({ 
	            url: getMainUrl(), 
	            params: { 
	               action: "dummy" 
	              }, 
	            success: function(response){
	            	obj = Ext.util.JSON.decode(response.responseText);
	            	if (obj.success==false) {
                       	window.location = obj.target;	            		
	            	} else {
	            		if (obj.ret!=undefined && obj.ret!=VBUILD) {
					        Ext.Msg.confirm(_('Confirm'), _('A new version is avaiable. It is recommended to reload the page'),
								function(btn) {
						 			if (btn=="yes") {
						 				window.location.reload();	
						 			} 
						 		},this,Ext.Msg.INFO 
						 	);
	            		} else {
		            		setTimeout(keepAlive,KEEP_ALIVE);
		            	}
	            	}
	            },
				/*callback: function ( options, success, response ) { 
					setTimeout(keepAlive,KEEP_ALIVE);
				}*/
   });								
}

Ext.BLANK_IMAGE_URL="images/s.gif";

Ext.namespace("Verbum");

//Verbum = function(){};
Verbum = {version: 1};

function _(s) {
	if (typeof(i18n)!='undefined' && i18n[s]) {
		//return addslashes(i18n[s]);
		return i18n[s];
	}
	return s;
}

function jsonArray(records) {
	var json = "[";
	var key="";
	var value="";
	var rec="";
	for (var r=0;r<records.length;r++) {
		if (r>0) json +=", ";
		json += "{";
		rec = records[r];
		for (var f=0;f<rec.fields.keys.length;f++) {
			if (f>0) json +=", ";
			key = rec.fields.keys[f];
			value = rec.data[key];
			json += "\"" + key + "\": \"" + value + "\"";
		}
		json += "}";
	}
	json += "]";
	return json;
}

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function htmlEntitiesRender(value, p, record) {
	if (value!=undefined) return value.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"\\n");
}

function fetchFile(filename,op,name,mime) {
	 var ifrm = Ext.getBody().child('iframe.x-hidden:last');
	 if (ifrm==null) {
	 	ifrm = Ext.getBody().createChild({tag:'iframe',cls:'frame.x-hidden:last'});	
	 }
	var param = "?action=download&file="+filename;
	
	if (op!=undefined) {
		param = param + "&op="+op;
	}
	if (name!=undefined) {
		param = param + "&name="+name;
	}	
	if (mime!=undefined) {
		param = param + "&type="+mime;
	}
	ifrm.dom.src = param;
}

function uniqueId(str) {
	var txt = ((new Date().getTime()+random(10000,99999))* random(2,100)) + str + random(10000,99999999);  
	return Base64.encode(txt);
}

function focus(frm, fieldId) {
	var el = frm.findById(fieldId);
	if (el!=null) el.focus(false,true);	
}

function checkWidth(win,min,max) {
	if (min==undefined || min==null) {
		if (win.minWidth!=undefined) {
			min = win.minWidth;
		} else {
			min = 0;
		}
	}
	if (max==undefined || max==null) {
		if (win.maxWidth!=undefined) {
			max = win.maxWidth;
		} else {
			max = 0;
		}
	}
	if (win.getSize().width<min && min!=0) {
		console.log("adjust min width");
		win.setWidth(min);
	} else if (win.getSize().width>max && max!=0) {
		console.log("adjust max width");
		win.setWidth(max);
	}
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

/* EXTJS EXTEND */
Ext.apply(Ext.data.Connection.prototype, {
	timeout : ETMOUT
})

Ext.apply(Ext.grid.GridPanel.prototype, {
	loadMask: {msg: _('Loading...')}
})

Ext.apply(Ext.grid.GridView.prototype, {
	sortAscText: _('Sort Ascending'),
	sortDescText: _('Sort Descending'),
	columnsText: _('Columns')
})

Ext.apply(Ext.PagingToolbar.prototype, {
    displayMsg : _('Displaying {0} - {1} of {2}'),
    emptyMsg : _('No data to display'),
    beforePageText : _("Page"),
    afterPageText : _("of {0}"),
    firstText : _("First Page"),
    prevText : _("Previous Page"),
    nextText : _("Next Page"),
    lastText : _("Last Page"),
    refreshText : _("Refresh"),
})

Ext.apply(Ext.form.TextField.prototype, {
	blankText: _('This field is required'),
	invalidText: _('The value in this field is invalid'),
	maxLengthText: _('The maximum length for this field is {0}'),
	minLengthText: _('The minimum length for this field is {0}')
})

Ext.apply(Ext.form.VTypes.prototype, {
	emailText: _('This field should be an e-mail address in the format user@domain.com'),
	alphanumText : _('This field should only contain letters, numbers and _')
})

Ext.apply(Ext.ux.grid.GridFilters.prototype, {
	clearFilters: function(silent){
		if (silent) this.autoReload=false;
		this.filters.each(function(filter){
			filter.setActive(false);
		});
		if (silent) this.autoReload=true;
	}
})
	
Ext.apply(Ext.grid.EditorGridPanel.prototype, {
   startEditing : function(row, col){
        this.stopEditing();
        if(this.colModel.isCellEditable(col, row)){
            this.view.ensureVisible(row, col, true);
            var r = this.store.getAt(row);
            var field = this.colModel.getDataIndex(col);
            var e = {
                grid: this,
                record: r,
                field: field,
                value: r.data[field],
                row: row,
                column: col,
                cancel:false
            };
            if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
                this.editing = true;
                r.data[field] = e.value;
                var ed = this.colModel.getCellEditor(col, row);
                if(!ed.rendered){
                    ed.render(this.view.getEditorParent(ed));
                }
                (function(){                     ed.row = row;
                    ed.col = col;
                    ed.record = r;
                    ed.on("complete", this.onEditComplete, this, {single: true});
                    ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
                    this.activeEditor = ed;
                    var v = this.preEditValue(r, field);
                    ed.startEdit(this.view.getCell(row, col).firstChild, v);
                }).defer(50, this);
            }
        }
    }
});
 
    
Ext.apply(Ext.data.Store.prototype, {
    load : function(options){
        options = options || {};
        if(this.fireEvent("beforeload", this, options) !== false){
            this.storeOptions(options);
            var p = Ext.apply(options.params || {}, this.baseParams);
            if(this.sortInfo && this.remoteSort){
                var pn = this.paramNames;
                if (this.sortInfo.sortField==undefined) {
                	this.sortInfo.sortField = this.sortInfo.field;
                }
                p[pn["sort"]] = this.sortInfo.sortField;
                p[pn["dir"]] = this.sortInfo.direction;
            }
            this.proxy.load(p, this.reader, this.loadRecords, this, options);
            this.proxy.on({
            	'loadexception': function(obj,opt,response,e) {
            		res = Ext.util.JSON.decode(response.responseText);
            		if (res.target!=undefined) {
           				window.location = res.target;
           				return false;
            		}
            	}
            });
            return true;
        } else {
          return false;
        }
    },
    sort : function(fieldName, dir){
        var f = this.fields.get(fieldName);
        if(!f){
            return false;
        }
        if(!dir){
            if(this.sortInfo && this.sortInfo.field == f.name){
            	dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
            }else{
                dir = f.sortDir;
            }
        }
        var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
        var si = (this.sortInfo) ? this.sortInfo : null;

        this.sortToggle[f.name] = dir;
        
        var fname;
        if (f.sortField) {
        	fname = f.sortField;
        } else if (!f.mapping) {
        	fname = f.name;	
        } else {
        	fname = f.mapping;
        }
        this.sortInfo = {field: f.name, direction: dir, sortField: fname};
        
        if(!this.remoteSort){
            this.applySort();
            this.fireEvent("datachanged", this);
        }else{
            if (!this.load(this.lastOptions)) {
                if (st) {
                    this.sortToggle[f.name] = st;
                }
                if (si) {
                    this.sortInfo = si;
                }
            }
        }
    }
});
/*
Ext.apply(Ext.Msg, {

	error: function(text) {
		this.show({
			title: _('Error'),
			msg: text,
			buttons: this.OK,
			icon: this.ERROR 
		})
	},

	warn: function(text) {
		this.show({
			title: _('Notice'),
			msg: text,
			buttons: this.OK,
			icon: this.WARNING 
		})
	},
	
	message: function(text) {
		this.show({
			title: _('Verbum'),
			msg: text,
			buttons: this.OK
		})
	},

	info: function(text) {
		this.show({
			title: _('Verbum'),
			msg: text,
			buttons: this.OK,
			icon: this.INFO 
		})
	}
         
});
*/
Ext.apply(Ext.form.VTypes, {
  daterange: function(val, field) {
    var date = field.parseDate(val);
    
    // We need to force the picker to update values to recaluate the disabled dates display
    var dispUpd = function(picker) {
      var ad = picker.activeDate;
      picker.activeDate = null;
      picker.update(ad);
    };
    
    if (field.startDateField) {
      var sd = Ext.getCmp(field.startDateField);
      sd.maxValue = date;
      if (sd.menu && sd.menu.picker) {
        sd.menu.picker.maxDate = date;
        dispUpd(sd.menu.picker);
      }
    } else if (field.endDateField) {
      var ed = Ext.getCmp(field.endDateField);
      ed.minValue = date;
      if (ed.menu && ed.menu.picker) {
        ed.menu.picker.minDate = date;
        dispUpd(ed.menu.picker);
      }
    }
    /* Always return true since we're only using this vtype
     * to set the min/max allowed values (these are tested
     * for after the vtype test)
     */
    return true;
  },
  
  password: function(val, field) {
    if (field.initialPassField) {
      var pwd = Ext.getCmp(field.initialPassField);
      return (val == pwd.getValue());
    }
    return true;
  },
  
  passwordText: _('Passwords do not match'),
  
  checkList: function(val, field) {
    if (field.cmpField) {
      var orig = Ext.getCmp(field.cmpField);
      return (field.getValue() == orig.getValue());
    }
    return true;
  },
  
  checkListText: '',
  
  equal: function(val, field) {
    if (field.cmpField) {
      var orig = Ext.getCmp(field.cmpField);
      return (val == orig.getValue());
    }
    return true;
  },
  
  equalText: _('The e-mail and its verification does not match.')

});

function setPref(name,value) {
	createCookie("verbum["+name+"]",value,COOKIE_EXPIRE);
}

function getPref(name) {
	var v = readCookie("verbum["+name+"]");
	if (v!=null) {
		if (v=="true") {
			v=true;
		} else if (v=="false") {
			v=false;
		}
	}
	return v;
}

function clearPref(name) {
	eraseCookie("verbum["+name+"]");
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


/*
// old school cookie functions
var Cookies = {};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};*/
